import { getDetail } from '@/api/user';
import type { IUser } from '@/typings/interface';
import { delayNavigateTo } from '@/utils/navigator';

export const useUser = defineStore(
  'user',
  () => {
    let isLogin = ref<boolean>(false);
    let token = ref<string>('');
    let details = ref<IUser>();
    async function switchLoginState(_token: string) {
      token.value = _token;
      isLogin.value = true;
      await syncUserInfo();
      delayNavigateTo('/pages/index/index');
    }

    // 获取用户信息
    async function syncUserInfo() {
      if (!token.value || !isLogin.value) return;
      details.value = (await getDetail()).data;
    }
    // 退出登录
    function logout() {
      token.value = '';
      isLogin.value = false;
      details.value = {} as any;
    }
    return ({ isLogin, token, switchLoginState, syncUserInfo, details,logout, });
  },
  { persist: true }
);

